import axios from '@ohos/axios';
import Prompt from '@system.prompt';
import { baseUrl } from '../constants/baseUrl';

export interface ResponseType<T> {
  code: number;
  message: string;
  data: T;
  ok: boolean;
}

const request = axios.create({
  baseURL: baseUrl,
  timeout: 20000,
})

request.interceptors.request.use(
  (config) => {
    const token = AppStorage.Get('token') as string;
    if (token) {
      config.headers.token = token;
    }
    return config;
  }
)

request.interceptors.response.use(
  (response) => {
    const data = response.data;
    if (data.code === 200) {
      return data.data;
    } else {
      const message = data.message;
      Prompt.showToast({ message })
      return Promise.reject(message);
    }
  },
  (error) => {
    const message = error.message;
    Prompt.showToast({ message })
    return Promise.reject(message);
  }
)

export default request;